package com.meeting.y.controller;

import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.swagger.annotation.ActionApi;
import com.jfinal.swagger.annotation.Api;
import com.jfinal.swagger.annotation.Param;
import com.jfinal.swagger.annotation.Params;
import com.jfinal.upload.UploadFile;
import com.meeting.y.model.*;
import com.meeting.y.model.base.BaseToyToys;
import com.meeting.y.util.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.*;

@Api(remark="YtoyController，小程序 玩具库接口", sort=2)
public class YtoyController extends Controller {
    private static final Logger logger = LoggerFactory.getLogger(YtoyController.class);


    @ActionApi(remark = "保存玩具信息")
    @Params({
            @Param(name = "id", remark = "玩具id", defaultValue = "8"),
            @Param(name = "name", remark = "玩具name", defaultValue = "溜溜球"),
            @Param(name = "barcode", remark = "玩具条形码", defaultValue = "2323232"),
            @Param(name = "type", remark = "玩具类型", defaultValue = "1"),
            @Param(name = "agefrom", remark = "月龄开始", defaultValue = "6"),
            @Param(name = "ageto", remark = "月龄结束", defaultValue = "12"),
            @Param(name = "remark", remark = "说明", defaultValue = "锻炼手指，精细")
    })
    public void toy_save() {
        ToyToys toyToys = getModel(ToyToys.class,"");
        if(toyToys.getType()!=null){
            toyToys.setType(toyToys.getType()+1);
        }
        toyToys.setCreateUserId(YmeetingController.getCurrentRelaUserId(this.getRequest()));
        ToyToys.dao.saveOrUpdateToytoys(toyToys);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",toyToys.getInt("id") ));
    }

    @ActionApi(remark = "获取玩具信息")
    @Params({
            @Param(name = "id", remark = "玩具id", defaultValue = "8")
    })
    public void toy_info(@Para("id") Integer id){
        ToyToys toyToys = ToyToys.dao.findToytoysById(id);
        if(toyToys ==null){
            renderJson(Ret.fail("code", 404).set("message", "该玩具不存在"));
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", toyToys ));

    }

    @ActionApi(remark = "获取玩具借阅信息")
    @Params({
            @Param(name = "id", remark = "玩具id", defaultValue = "8")
    })
    public void toy_outrecord(@Para("id") Integer id){
        List<Record> result = ToyToys.dao.findToytoysOutRecord(id);

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", result ));

    }



    @ActionApi(remark = "获取玩具出借人")
    @Params({
            @Param(name = "id", remark = "玩具id", defaultValue = "8"),
            @Param(name = "userid", remark = "借阅人id", defaultValue = "8"),
    })
    public void toy_saveout(@Para("id") Integer id,@Para("userid") Integer userid){
        ToyToys toyToys = ToyToys.dao.findToytoysById(id);
        if(toyToys != null){
            Map resultmap = new HashMap();

            if(toyToys!=null){
                //校验 上一个 是否有人已经在使用。有的话，结束掉
                List<ToyCheckout> list = ToyCheckout.dao.findToycheckout(toyToys.getBarcode(),ToyCheckout.TOY_1_USEING);
                if(list.size()>0){
                    for(ToyCheckout toyCheckout:list){
                        toyCheckout.setStatus(ToyCheckout.TOY_3_TOUSER);
                        toyCheckout.setEndtime(new Date());
                        toyCheckout.setTouserId(userid);
                        ToyCheckout.dao.saveOrUpdateToycheckout(toyCheckout);
                    }
                }

                ToyCheckout toyCheckout = new ToyCheckout();
                toyCheckout.setBarcode(toyToys.getBarcode());
                toyCheckout.setToysId(toyToys.getId());
                toyCheckout.setStarttime(new Date());
                toyCheckout.setUserid(userid);
                toyCheckout.setStatus(ToyCheckout.TOY_1_USEING);
                ToyCheckout.dao.saveOrUpdateToycheckout(toyCheckout);
                resultmap.put("message","借阅成功");
            }else {
                resultmap.put("message","无法找到对应玩具，请先录入");
            }

        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",toyToys.toJson() ));

    }

    public void scan_get(@Para("barcode") String barcode){
        Integer userid = YmeetingController.getCurrentRelaUserId(this.getRequest());
        Map resultmap = new HashMap();

        ToyToys toyToys = ToyToys.dao.findToytoysByBarcode(barcode);
        if(toyToys!=null){
            //校验 上一个 是否有人已经在使用。有的话，结束掉
            List<ToyCheckout> list = ToyCheckout.dao.findToycheckout(barcode,ToyCheckout.TOY_1_USEING);
            if(list.size()>0){
                for(ToyCheckout toyCheckout:list){
                    toyCheckout.setStatus(ToyCheckout.TOY_3_TOUSER);
                    toyCheckout.setEndtime(new Date());
                    toyCheckout.setTouserId(userid);
                    ToyCheckout.dao.saveOrUpdateToycheckout(toyCheckout);
                }
            }

            ToyCheckout toyCheckout = new ToyCheckout();
            toyCheckout.setBarcode(barcode);
            toyCheckout.setToysId(toyToys.getId());
            toyCheckout.setStarttime(new Date());
            toyCheckout.setUserid(userid);
            toyCheckout.setStatus(ToyCheckout.TOY_1_USEING);
            ToyCheckout.dao.saveOrUpdateToycheckout(toyCheckout);
            resultmap.put("message","借阅成功");
        }else {
            resultmap.put("message","无法找到对应玩具，请先录入");
        }

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",resultmap ));

    }
    public void scan_return(@Para("barcode") String barcode){
        Integer userid = YmeetingController.getCurrentRelaUserId(this.getRequest());
        Map resultmap = new HashMap();

        ToyToys toyToys = ToyToys.dao.findToytoysByBarcode(barcode);
        if(toyToys!=null){
            boolean isadmin = YmeetingController.getCurrentUserIsAdmin(userid);
            Integer searchuser = userid;
            if(isadmin){
                searchuser = null;
            }
            List<ToyCheckout> list = ToyCheckout.dao.findToycheckout(barcode,ToyCheckout.TOY_1_USEING,searchuser);
            //一般角色 只能扫描自己的
            if(list.size()>0){
                for(ToyCheckout toyCheckout:list){
                    toyCheckout.setStatus(ToyCheckout.TOY_2_RETURN);
                    toyCheckout.setEndtime(new Date());
                    ToyCheckout.dao.saveOrUpdateToycheckout(toyCheckout);
                }
                //管理员可以 归还所有人的
            }else if(isadmin) {
                ToyCheckout toyCheckout = new ToyCheckout();
                toyCheckout.setBarcode(barcode);
                toyCheckout.setToysId(toyToys.getId());
                toyCheckout.setEndtime(new Date());
                toyCheckout.setUserid(userid);
                toyCheckout.setStatus(ToyCheckout.TOY_2_RETURN);
                toyCheckout.saveOrUpdateToycheckout(toyCheckout);
            }
        }else {
            resultmap.put("message","无法找到对应玩具，请先录入");
        }

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",resultmap ));

    }

    public void upload() {
        UploadFile ufile = getFile();//必须先调用改方法，否则，其他参数无法获取到，非常的坑。搞了好久
        if (ufile == null) {
            renderJson(Ret.fail().set("message", "无法找到文件"));
            return;
        }

        //題號	舊題號	題目		月齡 栏目
        String[] Class_PROPERTY = new String[]{"名称","编码","分类","月龄范围"};


        File file = ufile.getFile();

//        String _filepath = "C:\\work\\git\\one-JFinal-vue-element-admin\\";
//        String _filename = "1_PCDC新舊題號對照及月齡.xlsx";

//        File file = new File(_filepath+_filename);
        try {

            FileInputStream _in = new FileInputStream(file);
            Workbook workbook = UploadClassesController.parse(_in, "xlsx");
            Sheet sheet = workbook.getSheetAt(0);
            /*从B2开始读
             */

            //必须表头字段，动态表头，允许前三行任一行.headline 从开始的，行数减1
            Integer[] headNums = OfficeUtil.getHeadNums(0,Class_PROPERTY, sheet);
            if (headNums == null) {
                renderJson(Ret.fail().set("message", "表头不满足,请使用模板"));
                return;
            }


            Integer userid = 1;
            int rowNum = sheet.getPhysicalNumberOfRows();
            Map _columntype = RecordUtil.recordlistToMap(
                    MeetingEnum.dao.findMeetingenumList("toycolumns"),"name","value");
            Integer maxvalue = null;
            Integer maxsort = null;

            for (int rowIndex = 1; rowIndex < rowNum; rowIndex++) {
                try {
                    //信息验证
                     Log.getLog(this.getClass()).debug("------rowIndex" + rowIndex );
                    StringBuffer message = new StringBuffer();
                    Row row = sheet.getRow(rowIndex);
                    if (row == null) {
                        continue;
                    }
                    int cellNum = row.getPhysicalNumberOfCells();
                    if (cellNum > 0) {

//                        Cell cell = row.getCell(headNums[0]);//序号 非必填

//                        Cell cell1 = row.getCell(headNums[1]);//问题 题目 必填
//                        Cell cell2 = row.getCell(headNums[2]);//答案 必填 英文逗号分隔
//                        Cell cell3 = row.getCell(headNums[3]);//正确答案 不必填，目前没用
                        Cell cell4 = row.getCell(headNums[0]);//名称
                        Cell cell5 = row.getCell(headNums[1]);//编码
                        Cell cell6 = row.getCell(headNums[2]);//编码

//                        String no = OfficeUtil.getCellValue(cell);
//                        String quescontent = OfficeUtil.getCellValue(cell1);
                        String options = "是,否";//OfficeUtil.getCellValue(cell2);
                        String name = OfficeUtil.getCellValue(cell4);
                        String barcode = OfficeUtil.getCellValue(cell5);
                        String columntypename = OfficeUtil.getCellValue(cell6);
                        Integer colmntypeid = null;

                        if(StringUtil.isStrEmpty(name)){//todo，重名问题，需要处理
                            continue;
                        }

                        ToyToys toy = ToyToys.dao.findToytoysByBarcode(barcode);
                        if(toy == null) {
                            toy = new ToyToys();
                        }

                        if(_columntype.containsKey(columntypename)){
                            colmntypeid = NumberTool.safeToInteger(_columntype.get(columntypename),null);
                        }else{
                            Record maxrecord = MeetingEnum.dao.findMeetingenumMax("toycolumns");
                            Integer newvalue = NumberTool.safeToInteger(maxrecord.getStr("mvalue"),1);
                            Integer newsort = NumberTool.safeToInteger(maxrecord.getStr("msort"),1);

                            if(maxvalue ==null){ maxvalue = newvalue;}
                            if(maxsort ==null){ maxsort = newsort;}

                            MeetingEnum meetingEnum = new MeetingEnum();
                            meetingEnum.setMeetingEnumVal( ++maxvalue + "");
                            meetingEnum.setMeetingEnumSort( ++maxsort + "");
                            meetingEnum.setMeetingEnumKey("toycolumns");
                            meetingEnum.setMeetingEnumShowname(columntypename.trim());
                            meetingEnum.setUserId(userid);
                            meetingEnum.setModifyTime(new Date());
                            meetingEnum.save();
                            _columntype.put(columntypename.trim(),maxvalue);
                            colmntypeid = maxvalue;
                        }



                        toy.set("name",name);
                        toy.set("barcode",barcode);
                        toy.set("type",colmntypeid);
                        toy.set("modify_time",new Date());
                        toy.set("create_user_id",YmeetingController.getCurrentRelaUserId(this.getRequest()));

                        Integer quesid = ToyToys.dao.saveOrUpdateToytoys(toy);

                    }
                } catch (Exception e) {
                    Log.getLog(this.getClass()).debug("------rowIndex" + rowIndex);
                    e.printStackTrace();
                    break;
                }
            }
            

        } catch (Exception e) {
            Log.getLog(this.getClass()).debug("导入题目异常");
            e.printStackTrace();
            renderJson(Ret.fail().set("message", "导入题目异常"));
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    /**
     * 获取玩具
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "取玩具 问题 选项 答案 关联关系")
    @Params({
            @Param(name = "surveyid", remark = "玩具id", defaultValue = "8")
    })
    public void toy_list(){

        Integer _type = getParaToInt("type");//目前都 0，后面转换为了 null不查询。

        String _searchkey = getPara("searchkey");
//        List<Record> _result = WechatUser.dao.findWechatuserByType(_type, _searchkey);
        List<Record> _result = ToyToys.dao.findToytoys(_type ==0?null:_type,_searchkey);

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }


    /**
     * 获取玩具 问题 选项 答案 关联关系
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "取玩具 问题 选项 答案 关联关系")
    @Params({
            @Param(name = "surveyid", remark = "玩具id", defaultValue = "8")
    })
    public void toy_managerlist(){
        String _type = getPara("type");
        String _searchkey = getPara("searchkey");
        logger.debug("--------------------_searchkey:"+_searchkey);
        logger.debug("--------------------_searchkey:"+_searchkey);
        List<Record> _result = WechatUser.dao.findWechatuserByType(_type, _searchkey);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
        if(true) {
            return;
        }

        List<Record> result = new PaperDao().getPaperRela(1);

        Map resultmap = new HashMap();
        Map answer_usermap = new HashMap();
        for(Record record:result){
            Integer answerid = record.getInt("answerid");
            Integer userid = record.getInt("userid");
            answer_usermap.put(answerid,userid);
        }
        resultmap.put("answer_user",answer_usermap);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",resultmap ));
    }


}
